<?php

namespace Service;

use EvaluationModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use UserModel;
use UserOrgInfoModel;
use UserPersonInfoModel;
use BannerModel;
use FundModel;
use UserMSModel;
use RiskLogModel;
use UserVerifaceRecordModel;
use PositionModel;
use Yaf\Registry;
use Illuminate\Http\Request;
use Wxxiong6\WxxLogger\WxxLogger as Logger;

class UserService extends BaseService
{
    private $userinfo_cache_key = "user:%s"; // 用户登录信息缓存 key
    private $forgetpwd_smscode_cache_key = "sms-code-forgetpwd:%s"; // 用户登录信息缓存 key
    private $login_failed_count_key = "login_faield:%s";            // 设置登录失败session key

    //身份证是否长期有效
    const is_long_effective = [
        0 => '否',
        1 => '是',
    ];

    //婚姻状态
    const marriage = [
        0 => '未婚',
        1 => '已婚',
    ];

    //职业 1.党政机关，事业单位 2.企业单位 3.自由业主 4.学生 5.军人 6.其他
    const vocational_type = [
        1 => '党政机关，事业单位',
        2 => '企业单位',
        3 => '自由业主',
        4 => '学生',
        5 => '军人',
        6 => '其他',
    ];

    //性别
    const sex = [
        0 => '女',
        1 => '男',
    ];
    //证件类型 1:身份证 2：营业执照
    const custodian_id_type = [
        1 => '身份证',
        2 => '营业执照',
    ];

    const is_expert = [
        0 => '普通投资者',
        1 => '专业投资者',
    ];
    //企业性质 1.党政机关，2，事业单位 3.有限公司 4.股份公司 5.合伙企业 6.财团法人 7.其他组织
    const company_property = [
        1 => '党政机关',
        2 => '事业单位',
        3 => '有限公司',
        4 => '股份公司',
        5 => '合伙企业',
        6 => '财团法人',
        7 => '其他组织',
    ];
    //产品类型
    const product_type = [
        1 => '证券公司资产管理产品',
        2 => '基金管理公司及其子公司产品',
        3 => '期货公司资产管理产品',
        4 => '银行理财产品',
        5 => '保险产品',
        6 => '信托产品',
        7 => '经行业协会备案的私募产品',
    ];

    //机构补充信息性别
    const person_gender = [
        0 => '男',
        1 => '女',
    ];
    //是否承诺无不诚信信息 1：否 2：是
    const promise = [
        1 => '是',
        2 => '否',
    ];

    const is_financial_industry = [
        1 => '不属于',
        2 => '属于',
    ];
    // 用户表查询字段
    public $fileds = [
        'id',
        'e_id',
        'cellphone',
        'pwd',
        'username',
        'user_img',
        'sex',
        'identity_id',
        'organization_name',
        'business_license_number',
        'id_type',
        'nick_name',
        'certificate_valid_date',
        'is_private_fund_status',
        'nationality',
        'vocational_type',
        'register_status',
        'promise',
        'type',
        'lowest_grade',
        'investor',
        'login_count',
        'last_login_time',
        'first_edit',
    ];

    //查询个人用户步骤1数据
    public $person_step_one = [
        'is_long-effective',
        'certificate_valid_date',
        'marriage',
        'vocational_type',
        'relation_address',
        'zip_code',
        'sex',
        'nationality',
    ];
    //查询个人用户步骤2数据
    public $person_step_two = [
        'custodian_name',
        'custodian_id_type',
        'custodian_identity_id',
        'custodian_certificate_date',
    ];
    //查询个人用户步骤3数据
    public $person_step_three = [
        'net_asset',
        'financial_net_asset',
        'recent_three_years_reincome',
        'invest_term',
        'related_work_term',
        'is_financial_industry',
        'promise',
    ];
    //查询个人用户步骤4数据
    public $person_step_four = [
        'recent_one_years_reincome',
        'recent_one_financial_assets',
        'invest_term',
        'promise',
        'is_financial_industry',
    ];


    //查询用户补充信息数据
    public $person_supplement_info = [
        'is_expert',
        //    'title',
        'promise_benifit_self',
    ];


    //查询机构用户步骤1数据
    public $org_step_one = [
        'company_property',
        'business_license_number',
        'relation_address',
    ];
    //查询机构用户步骤2数据
    public $org_step_two = [
        'is_financial_industry_company',
        'is_financial_products_company',
        'is_social_security_funds_company',
    ];
    //查询机构用户步骤3数据
    public $org_step_three = [
        'net_asset',
        'financial_net_asset',
        'recent_three_years_reincome',
        'invest_term',
        'related_work_term',
    ];

    //查询机构用户步骤1数据
    public $org_user_step_one = [
        'legal_person_name',
        'legal_person_card',
        'legal_person_vailddate',
        'long_effective_l',
        'legal_person_gender',
        'auth_person_name',
        'auth_person_card',
        'auth_person_vailddate',
        'long_effective_a',
        'auth_person_gender',
        'auth_title',
        'legal_person_vailddate',
    ];
    //查询机构用户步骤2数据
    public $org_user_step_two = [
        'product_type',
        'fill_org_name',
        'fill_time',
        'create_date',
        'fill_num',
        'continue_time',
        'product_size',
        'product_manager',
        'manager_qualification',
        'manager_num',
        'product_controller',
    ];

    // 个人用户附加信息查询字段
    public $person_fileds = ['title', 'promise_benifit_self', 'is_expert',];

    // 机构用户附加信息查询字段
    public $org_fileds = [
        'name',
        'org_type',
        'card',
        'register_money',
        'vailddate',
        'product_type',
        'promise_benifit_self',
        'is_expert',
        'auth_person_card',
        'legal_person_card',
    ];

    // 用户评测相关字段
    public $evaluation_fileds = ['grade_int', 'grade', 'risklevel', 'description',];

    // 提交测评查询用户字段
    public $user_fileds = [
        'id',
        'username',
        'identity_id',
        'cellphone',
        'type',
        'id_type',
        'e_id',
        'organization_name',
        'business_license_number',
    ];

    /**
     * 登录
     * @param $cellphone
     * @param $password
     * @return array
     * @throws \Exception
     */
    public function login($cellphone, $password)
    {
        $userInfo = "";
        $result = UserModel::select($this->fileds)->where('cellphone', $cellphone)->get();
        if (!$result->isEmpty()) {
            $userModel = $result->first();
            $userAttributes = $userModel->toArray();

            if ($userAttributes['pwd'] != $password) {
                throw new \Exception("手机号或密码错误", LOGIN_FAILED);
            }

            // 获取附加信息
            $userInfo = $this->getUserInfo($userAttributes);

            $userModel->login_count += 1;
            $userModel->last_login_time = date("Y-m-d H:i:s");
            $userModel->save();
            // 生成auth token
            $tokenInfo = App::createToken($userAttributes['id']);
            $userInfo['token'] = $tokenInfo['token'];
            $userInfo['token_expire'] = $tokenInfo['expire'];
        } else {
            throw new \Exception("用户未注册", LOGIN_UNKNOWN_USERNAME);
        }

        if (isset($userInfo['pwd'])) {
            unset($userInfo['pwd']);
        }
        $this->createUserInfoCache($userInfo);

        return $userInfo;
    }

    public function getUserByStep($step, $type, $id)
    {
        $result = [];
        if ($type == 1) { //个人
            switch ($step) {
                case 1:
                    $result = UserModel::select($this->person_step_one)->where('id', $id)->first()->toArray();
                    $msRes = UserMSModel::select('status')->where('user_id', $id)->orderBy('id', 'desc')->first();
                    if (isset($msRes->status) && $msRes->status == 2) {
                        $result['status'] = 2; //认证通过
                        $result['status_txt'] = '已认证';
                    } else {
                        $result['status'] = 1;
                        $result['status_txt'] = '未认证';
                    }
                    break;
                case 2:
                    $result = UserModel::select($this->person_step_two)->where('id', $id)->first()->toArray();
                    // $result['custodian_id_type'] = self::custodian_id_type[$result['custodian_id_type']];
                    break;
                case 3:
                    $personInfo = UserModel::select($this->person_step_three)->where('id', $id)->first()->toArray();
                    $resultSupplementInfo = UserPersonInfoModel::select($this->person_supplement_info)->where('u_id',
                        $id)->first();
                    if (empty($resultSupplementInfo)) {
                        $result = $personInfo;
                        $result['promise_benifit_self'] = 1;
                    } else {
                        $result = array_merge($personInfo, $resultSupplementInfo->toArray());
                    }
                    // $result['is_expert'] = self::is_expert[$result['is_expert']];
                    //$result['promise_benifit_self'] = 1;
                    //$result['is_financial_industry'] = self::is_financial_industry[$result['is_financial_industry']];
                    break;
            }
        } else {
            if ($type == 2) { //机构
                switch ($step) {
                    case 1:
                        $userRes = UserModel::select($this->org_step_one)->where('id', $id)->first()->toArray();

                        $orgRes = UserOrgInfoModel::select('vailddate', 'is_expert', 'bls_photo')->where('u_id', $id)->first();
                        if (empty($orgRes)) {
                            $result = $userRes;
                        } else {
                            $result = array_merge($userRes, $orgRes->toArray());
                            //$result['is_expert'] = self::is_expert[$result['is_expert']];
                            $result['bls_photo'] = $orgRes['bls_photo'] ? getUploadHost() . $orgRes['bls_photo'] : '';
                        }

                        $msRes = UserMSModel::select('status')->where('user_id', $id)->orderBy('id', 'desc')->first();
                        if (isset($msRes->status) && $msRes->status == 2) {
                            $result['status'] = 2; //认证通过
                            $result['status_txt'] = '已认证';
                        } else {
                            $result['status'] = 1;
                            $result['status_txt'] = '未认证';
                        }
                        //$result['company_property'] = (!empty($result['company_property']) && isset(self::company_property[$result['company_property']])) ?
                        //                               self::company_property[$result['company_property']] : '';
                        break;
                    case 2:
                        $result = UserModel::select($this->org_step_two)->where('id', $id)->first()->toArray();
                        break;
                    case 3:
                        $userRes = UserModel::select($this->person_step_four)->where('id', $id)->first()->toArray();
                        $orgRes = UserOrgInfoModel::select('promise_benifit_self')->where('u_id', $id)->first();
                        if (empty($orgRes)) {
                            $result = $userRes;
                            $result['promise_benifit_self'] = 0;
                        } else {
                            $result = array_merge($userRes, $orgRes->toArray());
                        }
                        break;
                }
            }
        }
        return $result;
    }

    public function getOrgUserByStep($step, $id)
    {
        $result = [];
        switch ($step) {
            case 1:
                $result = UserOrgInfoModel::select($this->org_user_step_one)->where('u_id', $id)->first();
                if (!empty($result)) {
                    $result = $result->toArray();
                    // $result['legal_person_gender'] = !empty($result['legal_person_gender']) ? self::person_gender[$result['legal_person_gender']] : '';
                    // $result['auth_person_gender'] = !empty($result['auth_person_gender']) ? self::person_gender[$result['auth_person_gender']] : '';
                }
                break;
            case 2:
                $result = UserOrgInfoModel::select($this->org_user_step_two)->where('u_id', $id)->first();
                if (!empty($result)) {
                    $result = $result->toArray();
                    // $result['product_type'] = !empty($result['product_type']) ? self::product_type[$result['product_type']] : '';
                }
                break;
            default:
                $result = [];
        }

        return $result;
    }

    /*
     * 获取用户附加信息
     */
    public function getUserInfo($user)
    {
        // 个人用户
        $user_info = [];
        if ($user['type'] == 1) {
            $res = UserPersonInfoModel::select($this->person_fileds)->where('u_id', $user['id'])->get();
            if (!$res->isEmpty()) {
                $user_info = $res->first()->toArray();
            }
        } // 企业用户
        elseif ($user['type'] == 2) {
            $res = UserOrgInfoModel::select($this->org_fileds)->where('u_id', $user['id'])->get();
            if (!$res->isEmpty()) {
                $user_info = $res->first()->toArray();
            }
        }

        // 获取评测相关信息
        $evaluation_info = ['score' => "0分", 'datetime' => ""];
        if ($user['e_id']) {
            $evaluationModel = EvaluationModel::find($user['e_id']);
            if ($evaluationModel) {
                $evaluation_info = $this->getGrade($evaluationModel->evaluation_score);
                $evaluation_info['score'] = $evaluationModel->evaluation_score . '分';
                $evaluation_info['datetime'] = date("Y-m-d H:i:s", $evaluationModel->add_time);
            }
        }
        $riskNum = RiskLogModel::where('status', '0')->where('uid', $user['id'])->count();
        $user['risk_num'] = $riskNum;
        // 其他需要加工处理的字段
        $user['investor_txt'] = $user['investor'] == 1 ? "已认证" : "未认证";
        $user['e_id'] = !empty($user['e_id']) ? $user['e_id'] : 0;

        $return = array_merge($user, $user_info, $evaluation_info);
        return $return;
    }

    /**
     * redis 缓存用户信息
     * @param $user
     * @return bool
     */
    public function createUserInfoCache($user)
    {
        $cache_key = sprintf($this->userinfo_cache_key, $user['id']);

        $ex_fileds = $user['type'] == 1 ? $this->person_fileds : $this->org_fileds;
        $fields = array_merge($this->fileds, $ex_fileds, $this->evaluation_fileds);

        $data = [];
        array_walk($fields, function ($field) use (&$data, $user) {
            if (isset($user[$field]) && !empty($user[$field])) {
                $data[$field] = $user[$field];
            } else {
                // for string
                $data[$field] = "";

                // for integer;
                in_array($field,
                    ['grade_int', 'org_type', 'is_expert', 'investor', 'promise_benifit_self']) && $data[$field] = 0;
            }
        });

        Redis::hmset($cache_key, $data);
        Redis::expire($cache_key, 3600 * 24 * 7);
        return true;
    }

    /**
     * 删除用户信息缓存
     * @param $uid
     * @return bool
     */
    public function deleteUserInfoCache($uid)
    {
        $cache_key = sprintf($this->userinfo_cache_key, $uid);
        Redis::del($cache_key);
        return true;
    }

    /**
     * 更新用户信息缓存
     * @param $user
     */
    public function updateUserInfoCache($user)
    {
        $cache_key = sprintf($this->userinfo_cache_key, $user['id']);
        Redis::hmset($cache_key, $user);
        Redis::expire($cache_key, 3600 * 24 * 7);
        return true;
    }

    /**
     * redis 获取用户信息
     * @param $uid
     * @return array|mixed
     */
    public function getUserInfoCache($uid, $field = "")
    {
        $key = sprintf($this->userinfo_cache_key, $uid);
        if (!empty($field)) {
            $res = Redis::hget($key, $field);
        } else {
            $res = Redis::hgetall($key);
        }

        return $res;
    }

    /**
     * @param $score 测评分数
     * @return array 风险测评结果
     */
    public function getGrade($score)
    {

        $score = intval($score);


        if (0 <= $score && $score <= 20) {
            $gradeArr = [
                'grade_int' => 1,
                'grade' => '保守型C1',
                'risklevel' => '低R1',
                'description' => '•希望本金安全，收益稳定，不能接受价格波动•不愿意承担风险以换取高收益•不太在意资金是否有较大升值'
            ];
        } elseif (21 <= $score && $score <= 40) {
            $gradeArr = [
                'grade_int' => 2,
                'grade' => '稳健型C2',
                'risklevel' => '低R1、中低R2',
                'description' => '•希望本金安全，收益稳定，能接受较小的价格波动•追求低风险，对投资回报要求不高•在保证本金安全的基础上，希望取得一定增值收入'
            ];
        } elseif (41 <= $score && $score <= 60) {
            $gradeArr = [
                'grade_int' => 3,
                'grade' => '平衡型C3',
                'risklevel' => '低R1、中低R2、中R3',
                'description' => '•能接受适中的价格波动•通常愿意承担一定的投资风险•偏好投资兼具稳定性及收益性的产品'
            ];
        } elseif (61 <= $score && $score <= 80) {
            $gradeArr = [
                'grade_int' => 4,
                'grade' => '成长型C4',
                'risklevel' => '低R1、中低R2、中R3、中高R4',
                'description' => '•能接受较大的价格波动•愿意承担较高的投资风险，博取较高收益•偏好投资兼具成长性及收益性的产品'
            ];
        } elseif (81 <= $score && $score <= 100) {
            $gradeArr = [
                'grade_int' => 5,
                'grade' => '进取型C5',
                'risklevel' => '低R1、中低R2、中R3、中高R4、高R5',
                'description' => '•资产市值波动比较大，能够接受可能出现的较大亏损•能承担全部收益包括本金可能损失的风险，预期收益率较高•偏好投资高成长性的产品，希望投资较快的增长，尽可能获得更高回报'
            ];
        } else {
            $gradeArr = [
                'grade_int' => 1,
                'grade' => '保守型C1',
                'risklevel' => '低R1',
                'description' => '•希望本金安全，收益稳定，不能接受价格波动•不愿意承担风险以换取高收益•不太在意资金是否有较大升值'
            ];
        }
        return $gradeArr;
    }

    /**
     * 验证手机短信验证码
     * @param $cellphone 手机号码
     * @param $sms_code  验证码
     * @param int $type 类型
     * @return array
     */
    public function checkVerifyCode($cellphone, $sms_code, $type = 1)
    {
        $res = ['status' => true, 'code' => "0000", 'msg' => ''];
        $key = "";
        $redis = Registry::get('redis');
        switch ($type) {
//            case 1:
//                $key = sprintf($this->forgetpwd_smscode_cache_key, $cellphone);
            case 4:
                $key = sprintf($this->forgetpwd_smscode_cache_key, $cellphone);
        }

        $verifyCode = $redis->get($key);
        if (!$verifyCode || ($verifyCode != $sms_code)) {
            $res['status'] = false;
            $res['code'] = SMS_CODE_ERROR;
            $res['msg'] = '验证码错误';
        } else {
            $ttl = Redis::ttl($key);
            if ($ttl + 300 < 3600 * 24) {
                $res['status'] = false;
                $res['code'] = SMS_CODE_ERROR;
                $res['msg'] = '验证码已失效';
                return $res;
            }
            Redis::del($key);
        }

        return $res;
    }


    /**
     * 获取首页数据
     */
    public function getHomePageData($uid, $page = 1)
    {
        $doMain = !empty(getCommonConfig('app_attachment_path')) ? getCommonConfig('app_attachment_path') : "";
        $data = [];
        $par = [];
        $bannelFields = ['name', 'sort', 'img'];
        $fundFields = [
            'id',
            'fund_name',
            'fund_type',
            'products_size',
            'investment_term',
            'minimum_Money',
            'fund_pwd',
            'status',
            'risk_rank'
        ];


        $data['banner_list'] = [];
        $bannerModel = BannerModel::select($bannelFields)->where([
            'type' => '0',
            'status' => '2',
            'is_pc' => '1'
        ])->orderBy('sort', 'DESC')->get();
        if (!$bannerModel->isEmpty()) {
            foreach ($bannerModel as $k => $v) {
                $bannerModel[$k]['img'] = urlencode($doMain . $v['img']);
            }
            $data['banner_list'] = $bannerModel;
        }
        $data['list'] = [];
        $list = PositionModel::select(['content_id'])->where(['is_recommend' => '1'])->orderBy('list_sort',
            'ASC')->paginate('3', '', 'page', $page);
        $positionModel = $list->items();

        $data['page']['lastPage']    = $list->lastPage();
        $data['page']['perPage']     = $list->perPage();
        $data['page']['currentPage'] = $list->currentPage();

        if (!empty($positionModel)) {
            $position = array_column($positionModel, "content_id");
            $ids = implode(',', $position);
            $list = FundModel::select($fundFields)
                ->whereIn('id', $position)
                ->orderByRaw(("FIELD(id, $ids)"))
                ->get();
            $data['list'] = FundModel::classifyList($list, $uid);
        }


        return $data;
    }

    /**
     * 累计登录失败次数
     * @param $cellphone
     * @param bool $clear
     * @return int
     */
    public function loginErrorCount($cellphone, $clear = false)
    {
        $key = sprintf($this->login_failed_count_key, $cellphone);

        if ($clear) {
            Redis::del($key);
            return 1;
        }

        Redis::incrby($key, 1); // 累加登录失败次数
        Redis::expire($key, 3600 * 24);// 统计1天内失败次数
        $count = Redis::get($key);

        return $count;
    }


    /**
     * 保存问卷表信息
     * @param $userInfo
     * @param $score
     * @param $answer
     * @return int
     */
    public function saveEvaluation($userInfo, $score, $answer)
    {
        $uid = $userInfo['id'];
        $evaluation = EvaluationModel::select('id')->where('uid', $uid)->first();
        if (empty($evaluation)) {
            $evaluation = new EvaluationModel();
        }

        $evaluation->type = $userInfo['type'];
        $evaluation->uid = $uid;
        $evaluation->practice_mode = $userInfo['cellphone'];
        $evaluation->identity_type = $userInfo['id_type'];
        $evaluation->evaluation_score = $score;
        $evaluation->investor = 1;
        $evaluation->add_time = time();
        $evaluation->evaluation_fractional = $answer;
        $evaluation->uname = $userInfo['type'] == 1 ? $userInfo['username'] : $userInfo['organization_name'];
        $evaluation->identity_id = $userInfo['identity_id'];
        $evaluation->business_license_number = isset($userInfo['business_license_number']) ? $userInfo['business_license_number'] : '';
        $evaluation->save();

        $e_id = $evaluation->id;

        return $e_id;

    }


    /**
     * 处理产生风险异动 add 2017/12/29 by LiYang
     * @param $gradeInt
     * @param $uid
     * @return bool
     */
    public function privateRiskChange($gradeInt, $uid)
    {
        $info = UserVerifaceRecordModel::select('id')->where('uid', $uid)->get();
        if ($info->isEmpty()) {
            $this->logInfo($uid, '没有适当性需要处理,objectArray:' . var_export($info, true));
            return false;
        }

        //查询用户等级变化前的等级
        $gradeIntOld = $this->getUserInfoCache($uid, 'grade_int');

        //如果用户等级没有发生变化则不处理
        if ($gradeIntOld == $gradeInt) {
            $this->logInfo($uid, '用户等级没有发生变化,等级:' . $gradeIntOld);
            return false;
        }

        //查询该用户所有已预约记录
        $subscribeInfo = ConsulationService::getInstance()->getConsulationData($info, true);
        if (empty($subscribeInfo['list'])) {
            $this->logInfo($uid, '未找到预约记录:' . var_export($subscribeInfo, true));
            return false;
        }

        // 查询该用户所有已持有的预约产品等级
        $riskRankArr = $this->getProductRank($subscribeInfo['pid']);

        if (!$riskRankArr) {
            $this->logInfo($uid, '未找到产品等级');
            return false;
        }

        $dataAll = [];
        foreach ($subscribeInfo['list'] as $v) {

            if (!isset($riskRankArr[$v['pid']])) {
                $this->logInfo($uid, '未匹配到预约记录，产品ID：' . $v['pid']);
                continue;
            }

            //风险等级risk_rank 为0表示其他，产品要求按照保守型标识值1来计算
            if ($riskRankArr[$v['pid']] == 0) {
                $riskRankArr[$v['pid']] = 1;
            }

            //如果变动后用户等级高于产品等级，则不产生适当性
            if ($gradeInt >= $riskRankArr[$v['pid']]) {
                $this->logInfo($uid, '用户等级不低于产品等级,用户等级:' . $gradeInt . '产品等级：' . $riskRankArr[$v['pid']]);
                continue;
            }
            $dataAll[] = $this->riskData($v, $uid, $gradeInt, $riskRankArr[$v['pid']]);

        }

        $rows = $this->updateRisk($uid);
        $this->logInfo($uid, '将未处理的产品更新为重置,rows:' . $rows);

        $insRiskLog = RiskLogModel::insert($dataAll);

        $this->logInfo($uid, '生成适当性变动数据:' . var_export($insRiskLog, true));

        return $insRiskLog;
    }

    /**
     * 处理产生适当性异动数据
     * @param $v
     * @param $uid
     * @param $userLevel
     * @param $proLevel
     * @return array
     */
    public function riskData($v, $uid, $userLevel, $proLevel)
    {
        $data = [];
        $data['cid'] = $v['id'];
        $data['uid'] = $uid;
        $data['pid'] = $v['pid'];
        $data['username'] = $v['name'];
        $data['title'] = $v['fund_name'];
        $data['pro_level'] = $proLevel;
        $data['user_level'] = $userLevel;
        $data['status'] = 0;
        $data['create_time'] = date("Y-m-d H:i:s");
        $data['from_terminal'] = 1;
        return $data;
    }

    /**
     * 将未处理的产品更新为重置
     * @param $uid
     * @return mixed 受影响行数
     */
    public function updateRisk($uid)
    {
        $status['status'] = 1;
        $status['update_time'] = date("Y-m-d H:i:s");
        $status['from_terminal'] = 1;
        $rows = RiskLogModel::where('status', '0')
            ->where('uid', $uid)
            ->update($status);
        return $rows;
    }

    /**
     * 适当性处理记录日志
     * @param $uid
     * @param $msg
     * @return bool
     */
    public function logInfo($uid, $msg)
    {
        Logger::info('测评适当性提示：用户' . $uid . '返回结果：' . $msg);
    }


    /**
     * 如何存在则返回处理后的产品ID对应的产品等级
     * @param $proIdArr 用户预约的产品ID
     * @return array|bool
     */
    public function getProductRank($proIdArr)
    {

        if (!is_array($proIdArr) || empty($proIdArr)) {
            return false;
        }
        $riskRankObj = FundModel::select('id', 'risk_rank')->whereIn('id', array_unique($proIdArr))->get();

        if ($riskRankObj->isEmpty()) {
            return false;
        }
        $riskRankArr = array_column($riskRankObj->toArray(), 'risk_rank', 'id');

        return $riskRankArr;
    }

    /**
     * 验证身份证照片是否是本人
     * @param string $photoCardId 身份证照片识别出来的身份证号
     * @param int $userId 用户id
     * @param string $regUserCardId 注册身份证号
     * @param int $userType 用户类型
     * @return bool
     */
    public function checkCardPhoto($photoCardId, $regUserCardId, $userId, $userType) {
        if(empty($photoCardId)) {
            return false;
        }
        $userCardId = $regUserCardId;
        if ($userType == '2') {
            $userInfo = $this->getUserDetailInfo($userId, $userType);
            if (isset($userInfo['auth_person_card'])) {
                $userCardId = $userInfo['auth_person_card'] ;
            }
        }
        if (strncmp($photoCardId, $userCardId,6) === 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取用户详细信息
     * @param int $userId 用户信息
     * @param int $userType 用户尖
     * @return array
     */
    public function getUserDetailInfo($userId, $userType){
        $userInfo = [];
        if ($userType == 1) {
            $res = UserPersonInfoModel::select($this->person_fileds)->where('u_id', $userId)->get();
        } else if ($userType == 2) {
            $res = UserOrgInfoModel::select($this->org_fileds)->where('u_id', $userId)->get();
        }
        if (is_object($res) && !$res->isEmpty()) {
            $userInfo = $res->first()->toArray();
        }
        return $userInfo;
    }
}
